const { Controller } = require('egg');
const { service } = require('../utils/request');
const { downloadImageFromUrl } = require('../utils/index');
const FormData = require('form-data');
const { Readable } = require('stream');
class OdmController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.body = 'hi, egg';
  }
  async taskList() {
    // 任务列表
    const res = await service.get('/task/list');
    this.ctx.body = res.data;
  }
  async taskInfo(data) {
    const res = await service.get(`/task/${data.uuid}/info`);
    this.ctx.body = res.data;
  }
  async taskOutput() {
    const { ctx } = this;
    const res = await service.get('/task/8222db02-f68f-472a-97ec-f0d05c3ad05c/output');

    ctx.body = res.data;
  }
  // 重启任务
  async taskRestart() {
    const { ctx } = this;
    const res = await service.post('/task/restart', {
      options: {},
      uuid: '',
    });

    ctx.fbody = res.data;
  }
  //   删除任务
  async taskRemove(data) {
    const { ctx } = this;
    const res = await service.post('/task/remove', {
      uuid: data.uuid,
    });

    ctx.body = res.data;
  }
  // 向任务中添加图片
  async taskAddRes(data) {
    const { ctx } = this;
    try {
      // const data = {
      //   url: 'https://minio.flybo.online:9000/dj-bucket/data/29708105-ab7a-49a8-b043-24942db6922b/Remote-Control/DJI_20250811161331_0001_V.jpeg',
      //   uuid: '434d3fb3-b0e9-473c-8761-3ced6652b650',
      // };
      // 下载图片
      const webImage = await downloadImageFromUrl(data.url);
      // 创建FormData表单
      const form = new FormData();

      // 将Buffer转换为可读流，用于表单提交
      const imageStream = Readable.from(webImage.buffer);
      // 添加文件到表单（第三个参数是文件元数据）
      form.append('images', imageStream, {
        filename: webImage.filename,
        contentType: webImage.contentType,
      });
      console.log(form);
      const res = await service.post(`/task/new/upload/${data.uuid}`, form);
      ctx.body = res.data;
    } catch (err) {
      console.log('出错', err);
    }
  }

  // 初始化任务
  async taskInit(data) {
    const { ctx } = this;
    const res = await service.post(
      '/task/new/init',
      {
        images: '',
        uuid: data.uuid,
      },
      {
        headers: {
          'set-uuid': data.subtasks_id,
        },
      }
    );

    ctx.body = res.data;
  }
  // 开始任务
  async taskNewCommit(data) {
    const { ctx } = this;
    // data.uuid = '434d3fb3-b0e9-473c-8761-3ced6652b650';
    const res = await service.post(`/task/new/commit/${data.uuid}`, {});
    ctx.body = res.data;
  }
  // 取消任务
  async taskCancel() {
    const { ctx } = this;
    const res = await service.post('/task/cancel', {});

    ctx.body = res.data;
  }
  // async taskDownload() {
  //   const { ctx } = this;
  //   // 任务列表
  //   const res = await service.get('/task/8222db02-f68f-472a-97ec-f0d05c3ad05c/download/all.zip');

  //   ctx.body = res.data;
  // }
}

module.exports = OdmController;
